﻿using System.Text.Json.Serialization;
using BCore.Identity.Users.Caching;
using Core.Caching;
using Core.Helpers;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Users.Features.Commands.AssignRole;

/// <summary>
/// 分配角色
/// </summary>
public class AssignRoleToUserCommand : ICacheInvalidatorRequest<Result<bool>>
{
    /// <summary>
    /// 用户Id
    /// </summary>
    public Guid UserId { get; set; }

    /// <summary>
    /// 角色Ids
    /// </summary>
    public List<Guid>? RoleIds { get; set; }

    [JsonIgnore]
    public IEnumerable<string>? Tags => UsersCacheKey.Tags;
}

public class AssignRoleToUserCommandHandler(IIdentityDbContext dbContext) : IRequestHandler<AssignRoleToUserCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(AssignRoleToUserCommand request, CancellationToken cancellationToken)
    {
        var user = await dbContext.Users
            .Include(u => u.UserRoles)
            .FirstOrDefaultAsync(x => x.Id == request.UserId, cancellationToken);
        ExceptionHelper.ThrowIfNull(user, "用户不存在");

        if (user!.UserRoles!.Any())
        {
            dbContext.UserRoles.RemoveRange(user!.UserRoles!);
            user!.ClearRoles();
        }

        if (request.RoleIds is { Count: > 0 })
        {
            foreach (var roleId in request.RoleIds)
                user.AssignRole(roleId);

            await dbContext.UserRoles.AddRangeAsync(user.UserRoles!);
        }

        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;
        return await Result<bool>.SucceedAsync(result, result, ["操作失败"]);
    }
}
